//提示信息对象
let notice;
//当前操作的列对象
let cols;
/**
 * 部门Id
 * @type number
 */
let deId;
let isSuccess; //表格对象
// import converterDate from '../learn/converterDate'
layui.config({
    base: '../lay/dist/'
});
layui.use(['form', 'table', 'laydate', 'notice', 'upload'], function () {
    var $ = layui.jquery,
        form = layui.form,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;
    notice = layui.notice;


    //<editor-fold desc="时间组件">
    // laydate.render({
    //     elem: '#date'
    //     , theme: '#393D49'
    // });
    //</editor-fold>

    //<editor-fold desc="添加功能">
    /**
     * 任务编号
     * @type {number}
     */
    let id = 0;
    /**'
     * 验证参数
     */
    form.verify({
        title: function (value, item) {
            if (value.length < 5) {
                return '任务名称至少得5个字符啊';
            }
        }, mess: value => {
            if (value.length < 4) {
                return "任务内容过短";
            } else if (value.length > 300) {
                return "内容内容过长"
            }
        }, score: v => {
            if (v < 1) {
                return "任务积分输入有误";
            }
        }
    })
    form.on('submit(saveBtn)', function (data) {
        data.field.deId = deId;
        if (id == 0) {
            send("/event/add", data.field);
        } else {
            data.field.id=id;
            send("/event/update", data.field);
            //刷新
            cols.update(data.field)
        }
        return false;
    })
    //</editor-fold>
    /**
     * 表格主题渲染
     */
    $(function () {
        deId = parseInt($("#deId").val());
        console.log(deId)
        table.render({
            elem: '#checkClass',
            url: '/event/all',
            where: {
                deId: deId
            },
            method: "post",
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [
                [
                    {
                        field: 'xid', width: 80, title: '序号', sort: true, templet: function (d) {
                            return d.LAY_INDEX;
                        }
                    },
                    {field: 'id', width: 100, title: 'ID', sort: true, hide: true},
                    // {
                    //     field: 'date', width: 150, title: '通知时间', sort: true,templet: function (d) {
                    //         return ConverterDate(d.date);
                    //     }
                    // },
                    {field: 'eventName', title: '任务名称',},
                    {field: 'eventMess', title: '任务内容'},
                    {field: 'eventRemark', title: '任务备注',},
                    {
                        field: 'state', title: '任务状态', templet: function (d) {
                            switch (d.state) {
                                case 0:
                                    return "未领取";
                                case 1:
                                    return "已领取";
                                case 2:
                                    return "已完成"
                                case 3:
                                    return "没完成"
                            }
                        }
                    },
                    {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
                ]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });
    });

    function send(url, data) {
        $.post(url,
            data
            , res => {
                if (res.success) {
                    notice.success("操作成功，刷新后显示")
                    layer.closeAll()
                    //清空内容；
                    clearAddContainer()
                } else {
                    notice.error("操作失败" + res.data)
                }
            }, "json");
    }


    /**
     * 监听搜索操作
     */
    form.on('submit(data-search-btn)', function (data) {
        let result = data.field;
        console.log(result)
        // return false
        //执行搜索重载
        table.reload('checkClass', {
            url: '/event/search'
            , where: {
                deId: deId,
                state: result.state,
                eventName: result.eventName
            }
        },);
        notice.success("搜索执行成功！");

        return false;
    });


    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'selectAll') { //
            table.reload('checkClass', {
                url: '/event/all'
            })
            notice.success("查询成功！");
        } else if (obj.event === 'addInfo') {
            id=0;
            layer.open({
                type: 1,
                area: ["50%", "60%"],
                shade: false,
                offset: 100,
                title: "添加任务", //不显示标题
                content: $('#addContainer'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        }
    });

    /**
     * 清空添加容器的内容
     */
    function clearAddContainer() {
        form.val("form", {
            eventRemark: "",
            eventMess: "",
            eventName: "",
            eventScore: ""
        })
    }


    /**
     * 工具行监听(删除/编辑)
     * */
    table.on('tool(currentTableFilter)', function (obj) {
        let data = obj.data;
        cols = obj;
        if (obj.event === 'edit') {
            id=data.id;
            //填充信息：
            form.val("form", {
                eventRemark: data.eventRemark,
                eventMess: data.eventMess,
                eventName: data.eventName,
                eventScore: data.eventScore
            })
            if (data.state != 0) {
                notice.error("该任务不允许编辑")
                return
            }
            layer.open({
                type: 1,
                area: ["50%", "60%"],
                shade: false,
                offset: 100,
                title: "编辑任务", //不显示标题
                content: $('#addContainer'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        } else if (obj.event === 'delete') {
            if (data.state != 0) {
                layer.msg("该任务不能被撤销");
            } else {
                layer.confirm('是否要撤销该任务？', function (index) {
                    $.post("/event/delete", {id: obj.data.id}, function (result) {
                        if (result.success) {
                            notice.success("删除成功！");
                            obj.del()
                        } else {
                            notice.error("删除失败！" + result.data);
                        }
                    }, "json")
                    layer.close(index);
                }, function (index) {
                    layer.close(index);
                }, 'json');
            }
        }else if (obj.event === 'dispose') {
            layer.confirm('该任务是否完成？', {
                btn: ['完成','未完成','取消处理'], //按钮
                btn1: function () {
                    dispose(data.id,2)
                },
                btn2:function () {
                    dispose(data.id,3)
                },
                btn3:function () {
                    layer.closeAll()
                }
            });
        }

    });

    function dispose(id,state) {
        $.post("/event/upState",{
            id:id,
            state:state
        },res=>{
            if (res.success) {
                cols.update({
                    state:state
                })
            } else {
                notice.error("操作失败" + res.data)
            }
            layer.closeAll()
        })

    }

    /**
     * 设置提示信息属性
     * @type {{hideEasing: string, positionClass: string, hideDuration: string, debug: boolean, closeButton: boolean, extendedTimeOut: string, showEasing: string, onclick: null, showDuration: string, iconClass: string, timeOut: string}}
     */
    notice.options = {
        closeButton: true,//显示关闭按钮
        debug: false,//启用debug
        positionClass: "toast-bottom-right",//弹出的位置,
        showDuration: "300",//显示的时间
        hideDuration: "1000",//消失的时间
        timeOut: "4000",//停留的时间
        extendedTimeOut: "1000",//控制时间
        showEasing: "swing",//显示时的动画缓冲方式
        hideEasing: "linear",//消失时的动画缓冲方式
        iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
        onclick: null, // 点击关闭回调
    };



});

/**
 * 子窗体编辑后父窗体动态改变
 * @param result 修改||添加的结果
 * @param childData
 */
function parentPage(childData) {
    layer.closeAll()
    if (childData) {
        cols.update({
            //更新列；
            id: childData.id,
            date: childData.date,
            className: childData.className,
            studentName: childData.studentName,
            classroomName: childData.classroomName
        });

    } else {
        isSuccess = true;
    }

}
